package com.forum.controller;

import com.forum.dto.LoginDTO;
import com.forum.dto.UserDTO;
import com.forum.resp.ResultData;
import com.forum.service.UserService;
import jakarta.validation.Valid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/")
public class UserController {
    private static final Logger logger = LogManager.getLogger(UserController.class);

    @Value("${forum.upload.path}")
    private String uploadPath;

    @Value("${forum.upload.url-prefix}")
    private String urlPrefix;

    @Autowired
    private UserService userService;

    @GetMapping("/getUser/{id}")
    public ResultData<UserDTO> getUser(@PathVariable Long id) {
        logger.debug("获取用户信息，用户ID: {}", id);
        return ResultData.success(userService.getUserById(id));
    }

    @PostMapping("/register")
    public ResultData<String> register(@RequestBody UserDTO userDTO) {
        logger.debug("用户注册请求，用户名: {}", userDTO.getUsername());
        userService.register(userDTO);
        logger.info("用户注册成功，用户名: {}", userDTO.getUsername());
        return ResultData.success("注册成功");
    }

    @PostMapping("/login")
    public ResultData<UserDTO> login(@Valid @RequestBody LoginDTO loginRequest) {
        logger.debug("用户登录请求，用户名: {}", loginRequest.getUsername());
        UserDTO userDTO = userService.login(loginRequest);
        logger.info("用户登录成功，用户名: {}", loginRequest.getUsername());
        return ResultData.success(userDTO);
    }

    @PutMapping("/update/{id}")
    public ResultData<String> updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
        logger.debug("更新用户信息，用户ID: {}", id);
        if (!id.equals(userDTO.getId())) {
            logger.warn("更新用户信息失败，路径ID与请求体ID不匹配，路径ID: {}, 请求体ID: {}", id, userDTO.getId());
            return ResultData.fail("400", "路径ID与请求体ID不匹配");
        }
        userService.updateUser(userDTO);
        logger.info("用户信息更新成功，用户ID: {}", id);
        return ResultData.success("用户信息更新成功");
    }

    @DeleteMapping("/del/{id}")
    public ResultData<String> deleteUser(@PathVariable Long id) {
        logger.debug("删除用户请求，用户ID: {}", id);
        userService.deleteUser(id);
        logger.info("用户删除成功，用户ID: {}", id);
        return ResultData.success("用户删除成功");
    }

    @GetMapping("/check-username")
    public ResultData<Boolean> checkUsername(@RequestParam String username) {
        logger.debug("检查用户名是否可用，用户名: {}", username);
        try {
            boolean available = userService.checkUsernameAvailable(username);
            logger.debug("用户名检查结果 - 用户名: {}, 是否可用: {}", username, available);
            return ResultData.success(available);
        } catch (Exception e) {
            logger.error("检查用户名时发生错误，用户名: {}, 错误: {}", username, e.getMessage());
            return ResultData.fail("500", "检查用户名失败");
        }
    }

    @PostMapping("/upload/{id}")
    public ResultData<String> uploadAvatar(@PathVariable Long id, @RequestParam("file") MultipartFile file) {
        logger.info("上传头像请求开始处理，用户ID: {}, 当前上传路径: {}", id, uploadPath);
        
        try {
            // 检查用户是否存在
            UserDTO user = userService.getUserById(id);
            if (user == null) {
                logger.warn("头像上传失败，用户不存在，用户ID: {}", id);
                return ResultData.fail("404", "用户不存在");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                logger.warn("头像上传失败，文件类型不支持: {}, 用户ID: {}", contentType, id);
                return ResultData.fail("400", "只能上传图片文件");
            }

            // 检查文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                logger.warn("头像上传失败，文件过大: {}MB, 用户ID: {}", file.getSize() / (1024 * 1024), id);
                return ResultData.fail("400", "文件大小不能超过5MB");
            }

            // 创建上传目录
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    logger.error("创建上传目录失败: {}", uploadPath);
                    return ResultData.fail("500", "服务器错误：无法创建上传目录");
                }
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(uploadPath, filename);
            Files.copy(file.getInputStream(), filePath);
            logger.info("文件已保存到物理路径: {}", filePath.toAbsolutePath());

            // 生成访问URL - 通过网关访问
            String fileUrl = "http://localhost:9000/api/user/uploads/" + filename;
            logger.info("生成的访问URL: {}", fileUrl);
            logger.info("资源应该可以通过路径映射 '/uploads/**' 访问, context-path为 '/user'");

            // 更新用户头像
            user.setPicture(fileUrl);
            userService.updateUser(user);

            logger.info("头像上传成功，用户ID: {}, 文件URL: {}", id, fileUrl);
            return ResultData.success(fileUrl);
        } catch (IOException e) {
            logger.error("头像上传失败，IO异常，用户ID: {}, 错误: {}", id, e.getMessage(), e);
            return ResultData.fail("500", "头像上传失败：" + e.getMessage());
        } catch (Exception e) {
            logger.error("头像上传失败，用户ID: {}, 错误: {}", id, e.getMessage(), e);
            return ResultData.fail("500", "头像上传失败：" + e.getMessage());
        }
    }
}
